#! /usr/bin/env python
# coding=utf-8
# 数据库操作

from google.appengine.ext import db
import random

class SimpleCounterShard(db.Model):
	#"""Shards for the counter"""
	count = db.IntegerProperty(required=True, default=0)   

NUM_SHARDS = 5

def get_count():
	#"""Retrieve the value for a given sharded counter."""
	total = 0
	for counter in SimpleCounterShard.all():
		total += counter.count
	return total

def increment(step):
	#"""Increment the value for a given sharded counter."""
	def txn():
		index = random.randint(0, NUM_SHARDS - 1)
		shard_name = "shard" + str(index)
		counter = SimpleCounterShard.get_by_key_name(shard_name)
		if counter is None:
			counter = SimpleCounterShard(key_name=shard_name)
		counter.count += step
		counter.put()
	db.run_in_transaction(txn)

def clearCount():
	q = db.GqlQuery("select * from SimpleCounterShard")
	for r in q:
		r.delete()

class LogInfo(db.Model):
	cronID = db.IntegerProperty(required=True)
	content = db.TextProperty()
	date = db.DateTimeProperty(auto_now_add=True)

def addLogInfo(log):
	if log:
		log.put()
		increment(1) #增加一个计数
		if get_count() >= 500:
			clearOldLog(50)

def listLogInfo():
	ls = []
	q = db.GqlQuery("select * from LogInfo order by date desc")
	for r in q:
		ls.append(r)
	return ls

def clearLog():
	q = db.GqlQuery("select * from LogInfo")
	for r in q:
		r.delete()
		#increment(-1) #减少一个计数
	clearCount()

def clearOldLog(count):
	q = db.GqlQuery("select * from LogInfo order by date asc")
	results = q.fetch(count)
	for r in results:
		r.delete()
		increment(-1) #减少一个计数

